import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import useEditorStore from '@/store/use-editor-store';
import { MinusIcon, PlusIcon } from 'lucide-react';
import { useState } from 'react';

const FontSizeButton = () => {
  const editor = useEditorStore((state) => state.editor);

  const currentFontSize = editor?.getAttributes('textStyle').fontSize
    ? editor.getAttributes('textStyle').fontSize.replace('px', '')
    : '16';

  const [fontSize, setFontSize] = useState(currentFontSize);
  const [inputValue, setInputValue] = useState(fontSize);
  const [isEditing, setIsEditing] = useState(false);

  const updateFontSize = (newSize: string) => {
    const size = parseInt(newSize, 10);
    if (!isNaN(size) && size > 0) {
      editor?.chain().focus().setFontSize(`${size}px`).run();

      setFontSize(newSize);
      setInputValue(newSize);
      setIsEditing(false);
    }
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleInputBlur = () => {
    updateFontSize(inputValue);
  };

  const handleKeydown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      e.preventDefault();

      updateFontSize(inputValue);
      editor?.commands.focus();
    }
  };

  const increaseFontSize = () => {
    const newSize = parseInt(fontSize, 10) + 1;

    updateFontSize(newSize.toString());
  };

  const decreaseFontSize = () => {
    const newSize = parseInt(fontSize, 10) - 1;

    if (newSize > 0) {
      updateFontSize(newSize.toString());
    }
  };

  return (
    <div className="flex items-center gap-x-0.5">
      <Button
        variant={'ghost'}
        className="h-7 w-7 shrink-0 flex items-center justify-center rounded-sm hover:bg-neutral-200/80"
        onClick={decreaseFontSize}
      >
        <MinusIcon className="size-4" />
      </Button>
      {isEditing ? (
        <Input
          className="h-7 w-10 text-sm text-center border border-neutral-400 rounded-sm 	bg-transparent focus:outline-none	focus:ring-0"
          value={inputValue}
          onChange={handleInputChange}
          onBlur={handleInputBlur}
          onKeyDown={handleKeydown}
        />
      ) : (
        <Button
          variant={'ghost'}
          className="h-7 w-10 text-sm text-center border border-neutral-400 rounded-sm hover:bg-neutral-200/80"
          onClick={() => {
            setIsEditing(true);
            setFontSize(currentFontSize);
          }}
        >
          {currentFontSize}
        </Button>
      )}
      <Button
        variant={'ghost'}
        className="h-7 w-7 shrink-0 flex items-center justify-center rounded-sm hover:bg-neutral-200/80"
        onClick={increaseFontSize}
      >
        <PlusIcon className="size-4" />
      </Button>
    </div>
  );
};

export default FontSizeButton;
